import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/login.vue'
import Home from './components/home.vue'
import Welcome from './components/welcome.vue'
import Users from './components/user/user.vue'
import Rights from './components/power/right.vue'
import Roles from './components/power/role.vue'
import Cate from './components/goods/cate.vue'
import Params from './components/goods/params.vue'
import List from './components/goods/list.vue'
import goodsAdd from './components/goods/goodsAdd.vue'
import order from './components/order/order.vue'
import report from './components/report/report.vue'
Vue.use(Router)

const router = new Router({
    routes: [
        // 重定向 ： 表示如果访问地址是/;那么重定向到 /login 这个地址
        { path: '/', redirect: '/login' },
        // 路由规则 当用户访问 /login 时会跳到login组件
        { path: '/login', component: Login },
        {
            path: '/home',
            component: Home,
            // 重定向，访问/home时，路径重定向到 /welcome 这个地址 
            redirect: '/welcome',
            children: [
                //welcome 主体区域使用welcome组件，因此welcome组件是 home的一个子路由
                // 最后一步不要走忘记 在home组件中放置welcome的路由占位符 
                { path: '/welcome', component: Welcome },
                { path: '/user', component: Users },
                { path: '/right', component: Rights },
                { path: '/role', component: Roles },
                { path: '/categories', component: Cate },
                { path: '/params', component: Params },
                { path: '/goodsList', component: List },
                { path: '/goodsAdd', component: goodsAdd },
                { path: '/orders', component: order },
                { path: '/report', component: report },
            ]
        },
    ]
})

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from 代表从哪个路径跳转而来
    // next 是一个函数 表示放行 next（） 表示放行； next('/login') 表示强制跳转
    if (to.path === '/login') return next();
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
        // 没有token 强制跳转到login 页面
    if (!tokenStr) return next('/login')
    next()
})

export default router